﻿CREATE PROCEDURE [Event].[CreateNewEvent]
  @OwnerID INT,
  @LocationID INT = NULL,
  @AttendeeListVisibilityID SMALLINT = 1,
	@EventTitle NVARCHAR(255),
	@Description NVARCHAR(1000) = NULL,
	@Cost MONEY = 0,
	@PaymentAccepted BIT = 0,
	@PaymentRefundable BIT = 0,
	@InvitationOnly BIT = 0,
	@Searchable BIT = 1,
	@SearchEngineURL NVARCHAR(200) = NULL,
	@EventID INT OUTPUT
WITH EXECUTE AS OWNER
AS
SET NOCOUNT ON;

BEGIN TRY
  BEGIN TRANSACTION;
  
  INSERT INTO Event.Events
  (
    OwnerID,
    LocationID,
    AttendeeListVisibilityID,
    Title,
    Description,
    Cost,
    PaymentAccepted,
    PaymentRefundable,
    InvitationOnly,
    Searchable,
    SearchEngineURL
  )
  VALUES
  (
    @OwnerID,
    @LocationId,
    @AttendeeListVisibilityID,
    @EventTitle,
    @Description,
    @Cost,
    @PaymentAccepted,
    @PaymentRefundable,
    @InvitationOnly,
    @Searchable,
    @SearchEngineURL
  )
  
  SET @EventID = SCOPE_IDENTITY();
  
  COMMIT TRANSACTION;
END TRY
BEGIN CATCH
  SET @EventID = -1;
  
  IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
  
  DECLARE @ERROR_SEVERITY AS INT,
          @ERROR_STATE AS INT,
          @ERROR_NUMBER AS INT,
          @ERROR_LINE AS INT,
          @ERROR_MESSAGE AS NVARCHAR(4000);

  SELECT @ERROR_SEVERITY = ERROR_SEVERITY(),
         @ERROR_STATE = ERROR_STATE(),
         @ERROR_NUMBER = ERROR_NUMBER(),
         @ERROR_LINE = ERROR_LINE(),
         @ERROR_MESSAGE = ERROR_MESSAGE();

  RAISERROR('Msg %d, Line %d, :%s',
            @ERROR_SEVERITY,
            @ERROR_STATE,
            @ERROR_NUMBER,
            @ERROR_LINE,
            @ERROR_MESSAGE);
END CATCH